package com.youlai.system.plugin.opcua;

import org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription;
import org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscriptionManager;
import org.eclipse.milo.opcua.stack.core.UaException;
import org.eclipse.milo.opcua.stack.core.types.builtin.DateTime;
import org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode;

public class CustomSubscriptionListener implements UaSubscriptionManager.SubscriptionListener {
    private OpcUaHelper opcUaHelper;


    CustomSubscriptionListener(OpcUaHelper opcUaHelper) {
        this.opcUaHelper = opcUaHelper;
    }

    public void onKeepAlive(UaSubscription subscription, DateTime publishTime) {
//        System.out.println("onKeepAlive");
        opcUaHelper.isConnected = true;
    }

    public void onStatusChanged(UaSubscription subscription, StatusCode status) {
//        System.out.println("onStatusChanged");
    }

    public void onPublishFailure(UaException exception) {
//        System.out.println("onPublishFailure");
//        opcUaHelper.isConnected = false;
    }

    public void onNotificationDataLost(UaSubscription subscription) {
//        System.out.println("onNotificationDataLost");
    }

    /**
     * 重连时 尝试恢复之前的订阅失败时 会调用此方法
     * @param uaSubscription 订阅
     * @param statusCode 状态
     */
    public void onSubscriptionTransferFailed(UaSubscription uaSubscription, StatusCode statusCode) {
//        System.out.println("恢复订阅失败 需要重新订阅");
        //在回调方法中重新订阅
        try {
            opcUaHelper.Connect();
            opcUaHelper.SubscriptionHandler();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
